// 欢迎页面功能
document.addEventListener('DOMContentLoaded', function() {
    // 加载数据
    loadJSON('data/content.json').then(data => {
        if (data) {
            // 填充页面内容
            document.getElementById('main-title').textContent = data.welcome.title;
            document.getElementById('sub-title').textContent = data.welcome.subtitle;
            document.getElementById('enter-text').textContent = data.welcome.enterText;
            
            // 初始化页面
            initWelcomePage(data);
        }
    });
});

// 初始化欢迎页面
function initWelcomePage(data) {
    // 创建初始蛋糕
    createCake();
    
    // 3秒后开始蛋糕爆炸动画
    setTimeout(() => {
        explodeCake();
        playSound('audio/explosion.mp3');
        
        // 显示页面元素
        setTimeout(() => {
            showPageElements();
            
            // 开始倒计时
            startCountdown(new Date(data.birthday));
            
            // 定期创建纸屑
            setInterval(() => {
                createConfetti(50);
            }, 5000);
        }, 1500);
    }, 1000);
    
    // 绑定进入按钮事件
    document.getElementById('enter-button').addEventListener('click', () => {
        // 播放进入音效
        playSound('audio/enter.mp3');
        
        // 创建烟花效果
        createFireworks(3);
        
        // 延迟跳转
        setTimeout(() => {
            window.location.href = 'memories.html';
        }, 1000);
    });
}

// 创建蛋糕
function createCake() {
    const container = document.getElementById('cake-container') || createContainer('cake-container');
    
    // 蛋糕底座
    const base = document.createElement('div');
    base.id = 'cake-base';
    base.className = 'cake-piece';
    base.style.width = '192px';
    base.style.height = '128px';
    base.style.backgroundColor = '#FF6B9B';
    base.style.borderRadius = '0 0 20px 20px';
    base.style.left = '50%';
    base.style.top = '60%';
    base.style.transform = 'translate(-50%, -50%)';
    base.style.opacity = '1';
    
    // 蛋糕上层
    const topLayer = document.createElement('div');
    topLayer.className = 'cake-piece';
    topLayer.style.width = '144px';
    topLayer.style.height = '96px';
    topLayer.style.backgroundColor = '#6BCBFF';
    topLayer.style.borderRadius = '0 0 20px 20px';
    topLayer.style.left = '50%';
    topLayer.style.top = '55%';
    topLayer.style.transform = 'translate(-50%, -50%)';
    topLayer.style.opacity = '1';
    
    // 蛋糕顶层
    const top = document.createElement('div');
    top.className = 'cake-piece';
    top.style.width = '96px';
    top.style.height = '64px';
    top.style.backgroundColor = '#FFD66B';
    top.style.borderRadius = '0 0 50% 50%';
    top.style.left = '50%';
    top.style.top = '50%';
    top.style.transform = 'translate(-50%, -50%)';
    top.style.opacity = '1';
    
    // 蜡烛
    const candle = document.createElement('div');
    candle.className = 'cake-piece';
    candle.style.width = '16px';
    candle.style.height = '48px';
    candle.style.backgroundColor = 'white';
    candle.style.borderRadius = '4px';
    candle.style.left = '50%';
    candle.style.top = '42%';
    candle.style.transform = 'translate(-50%, -50%)';
    candle.style.opacity = '1';
    
    // 火焰
    const flame = document.createElement('div');
    flame.className = 'cake-piece';
    flame.style.width = '12px';
    flame.style.height = '24px';
    flame.style.backgroundColor = '#FFE08C';
    flame.style.borderRadius = '50% 50% 20% 20%';
    flame.style.boxShadow = '0 0 15px #FFB74D';
    flame.style.left = '50%';
    flame.style.top = '38%';
    flame.style.transform = 'translate(-50%, -50%)';
    flame.style.opacity = '1';
    flame.style.animation = 'pulse 1s infinite alternate';
    
    container.appendChild(base);
    container.appendChild(topLayer);
    container.appendChild(top);
    container.appendChild(candle);
    container.appendChild(flame);
}

// 蛋糕爆炸动画
function explodeCake() {
    const container = document.getElementById('cake-container');
    if (!container) return;
    
    // 移除原蛋糕
    const oldPieces = container.querySelectorAll('.cake-piece');
    oldPieces.forEach(piece => piece.remove());
    
    // 创建蛋糕碎片
    const colors = ['#FF6B9B', '#FF87B0', '#FFA4C5', '#6BCBFF', '#8CD4FF', '#ACDFFF', '#FFD66B', '#FFE08C', '#FFF0B3'];
    const pieceCount = 50;
    
    for (let i = 0; i < pieceCount; i++) {
        const piece = document.createElement('div');
        piece.className = 'cake-piece';
        
        // 随机样式
        piece.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        const size = Math.random() * 20 + 10;
        piece.style.width = `${size}px`;
        piece.style.height = `${size}px`;
        
        // 位置在中心
        piece.style.left = '50%';
        piece.style.top = '50%';
        piece.style.transform = 'translate(-50%, -50%)';
        piece.style.opacity = '1';
        
        // 随机方向和旋转
        const angle = Math.random() * Math.PI * 2;
        const distance = Math.random() * 300 + 100;
        const x = Math.cos(angle) * distance;
        const y = Math.sin(angle) * distance;
        const rotation = Math.random() * 360;
        
        // 爆炸动画
        const duration = Math.random() * 2 + 1;
        piece.style.animation = `cake-explode ${duration}s ease-out forwards`;
        
        container.appendChild(piece);
        
        // 设置动画结束时的位置
        setTimeout(() => {
            piece.style.transform = `translate(${x}px, ${y}px) rotate(${rotation}deg)`;
        }, 50);
    }
    
    // 爆炸后创建纸屑
    setTimeout(() => {
        createConfetti(200);
    }, 500);
}

// 显示页面元素
function showPageElements() {
    // 逐个显示元素，添加淡入动画
    const elements = [
        'title-section',
        'countdown-section',
        'music-box-section',
        'enter-button-section'
    ];
    
    elements.forEach((id, index) => {
        setTimeout(() => {
            const element = document.getElementById(id);
            element.style.transition = 'opacity 0.8s ease';
            element.style.opacity = '1';
        }, index * 500);
    });
}

// 开始倒计时
function startCountdown(birthdayDate) {
    function updateCountdown() {
        const now = new Date();
        const diff = birthdayDate - now;
        
        // 如果生日已过，显示0
        if (diff <= 0) {
            document.getElementById('days').textContent = '0';
            document.getElementById('hours').textContent = '00';
            document.getElementById('minutes').textContent = '00';
            document.getElementById('seconds').textContent = '00';
            return;
        }
        
        // 计算天、时、分、秒
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((diff % (1000 * 60)) / 1000);
        
        // 更新显示
        document.getElementById('days').textContent = days;
        document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
        document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
        document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');
        
        // 秒数变化时添加动画
        const secondsElement = document.getElementById('seconds');
        secondsElement.style.animation = 'count-down 0.5s ease';
        setTimeout(() => {
            secondsElement.style.animation = '';
        }, 500);
    }
    
    // 立即更新一次
    updateCountdown();
    
    // 每秒更新一次
    setInterval(updateCountdown, 1000);
}

// 创建烟花效果
function createFireworks(count) {
    const container = document.getElementById('firework-container') || createContainer('firework-container');
    
    const colors = ['#FF6B9B', '#6BCBFF', '#FFD66B', '#A78BFA', '#6BFFB8'];
    
    for (let i = 0; i < count; i++) {
        // 随机位置
        const x = Math.random() * 80 + 10; // 10% - 90%
        const y = Math.random() * 50 + 20; // 20% - 70%
        
        // 随机颜色
        const color = colors[Math.floor(Math.random() * colors.length)];
        
        // 烟花数量
        const particleCount = Math.floor(Math.random() * 50) + 50;
        
        // 延迟发射
        setTimeout(() => {
            for (let j = 0; j < particleCount; j++) {
                const firework = document.createElement('div');
                firework.className = 'firework';
                
                // 样式
                firework.style.backgroundColor = color;
                const size = Math.random() * 4 + 2;
                firework.style.width = `${size}px`;
                firework.style.height = `${size}px`;
                
                // 位置
                firework.style.left = `${x}vw`;
                firework.style.top = `${y}vh`;
                
                // 动画
                const duration = Math.random() * 1 + 0.5;
                firework.style.animation = `firework-burst ${duration}s ease-out forwards`;
                
                container.appendChild(firework);
                
                // 动画结束后移除
                setTimeout(() => {
                    if (container.contains(firework)) {
                        container.removeChild(firework);
                    }
                }, duration * 1000);
            }
        }, i * 500);
    }
}

// 创建容器元素
function createContainer(id) {
    const container = document.createElement('div');
    container.id = id;
    document.body.appendChild(container);
    return container;
}

// 播放音效
function playSound(url) {
    const audio = new Audio(url);
    audio.volume = 0.5;
    audio.play().catch(e => console.log('播放音效失败:', e));
}
